<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px" @submit.prevent>
      <el-form-item label="料箱编号" prop="containerId">
        <el-input
          v-model.trim="queryParams.containerId"
          placeholder="请输入料箱编号"
          clearable
          @keyup.enter="handleQuery"
          style="width: 175px"
        />
      </el-form-item>
      <el-form-item label="料箱类型" prop="containerTypeName">
        <el-select
          v-model="queryParams.containerTypeName"
          placeholder="请选择料箱类型"
          clearable
          style="width: 175px"
          @change="handleQuery"
        >
          <el-option
            v-for="item in containerTypeList"
            :key="item.container_name"
            :label="item.container_name"
            :value="item.container_name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="格口数量" prop="compartmentCount">
        <el-select
          v-model="queryParams.compartmentCount"
          style="width: 175px"
          placeholder="请选择格口数量"
          @change="handleQuery"
        >
          <el-option
            v-for="item in compartmentCountList"
            :key="item.value"
            :label="item.value"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:container:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:container:remove']"
        >批量删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="batchAdd"
          v-hasPermi="['system:container:add']"
        >批量新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:container:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:container:export']"
        >导出</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Download"
          @click="downloadContainer"
        >下载导入模板</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <MyUpload
          buttonName="导入料箱" 
          url="/api/container/import"
          @success="handleUploadSuccess"
          @warning="handleUploadWarning"
        />
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <TableScrollContainer :topHeight="220">
      <template #default="{ tableHeight }">
    <el-table v-loading="loading" :data="containerList" @selection-change="handleSelectionChange" :height="tableHeight" border>
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="料箱编号" align="center" prop="containerId" sortable/> -->
      <el-table-column label="料箱编号" align="center" prop="containerId" />
      <el-table-column label="料箱类型" align="center" prop="containerTypeName" />
      <el-table-column label="所在厂区" align="center" prop="warehouseZonesName" />
      <el-table-column label="在库状态" align="center" prop="locationStatus">
        <template #default="scope">
          <dict-tag :options="location_status" :value="scope.row.locationStatus"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column label="料箱状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="container_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="锁定状态" align="center" prop="isLock">
        <template #default="scope">
          <dict-tag :options="container_lock_status" :value="scope.row.isLock"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column label="格口数量" align="center" prop="compartmentCount" />
      <el-table-column label="A箱面Code" align="center" prop="aboxFaceCode" />
      <el-table-column label="B箱面Code" align="center" prop="bboxFaceCode" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="190" fixed="right">
        <template #default="scope">
          <el-button type="success" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:container:edit']">修改</el-button>
          <el-button type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:container:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page-sizes="[10, 30, 50, 100]"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
      </template>
    </TableScrollContainer>

    <!-- 添加或修改料箱对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" :close-on-click-modal="false">
      <el-form ref="containerRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="料箱类型" prop="containerTypeId">
          <el-select
            v-model="form.containerTypeId"
            placeholder="请选择料箱类型"
            filterable
            clearable
            @change="selectType"
            @clear="resetTypeSelection"
          >
            <el-option
              v-for="item in containerTypeList"
              :key="item.container_type_id"
              :label="item.container_name"
              :value="item.container_type_id"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item v-if="currentMode === 'edit'" label="库区id" prop="warehouseZonesId">
          <el-input v-model="form.warehouseZonesId" placeholder="请输入库区id" />
        </el-form-item> -->
        <el-form-item v-if="selectTypeFlag" label="格口数量" prop="compartmentCount">
          <el-radio-group v-model="form.compartmentCount">
            <el-radio :value="20">20</el-radio>
            <el-radio :value="50">50</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 批量 -->
    <el-dialog title="批量新增" v-model="openBatch" width="500px" :close-on-click-modal="false">
      <el-form ref="containerBatchRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="新增数量" prop="batchCount">
          <el-input v-model.number="form.batchCount" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="料箱类型" prop="containerTypeId">
          <el-select
            v-model="form.containerTypeId"
            placeholder="请选择料箱类型"
            filterable
            clearable
            @change="selectType"
            @clear="resetTypeSelection"
          >
            <el-option
              v-for="item in containerTypeList"
              :key="item.container_type_id"
              :label="item.container_name"
              :value="item.container_type_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="selectTypeFlag" label="格口数量" prop="compartmentCount">
          <el-radio-group v-model="form.compartmentCount">
            <el-radio :value="20">20</el-radio>
            <el-radio :value="50">50</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormBatch" :loading="btn.batchAdd">确 定</el-button>
          <el-button @click="cancelBatch">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Container">
import { listContainer, getContainer, delContainer, addContainer, updateContainer, getContainerTypeAPI, batchAddAPI } from "@/api/work/container"
import { ElMessage } from 'element-plus'
import TableScrollContainer from '@/components/Pagetable/TableScrollContainer.vue'
const { proxy } = getCurrentInstance()
const { container_status, location_status, container_lock_status } = proxy.useDict('container_status', 'location_status', 'container_lock_status')
const containerList = ref([])
const open = ref(false)
const openBatch = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const currentMode = ref("")
const containerTypeList = ref([])
const selectTypeFlag = ref(false)
const compartmentCountList = ref([{value: 20}, {value: 50}])
const btn = reactive({
  batchAdd: false
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    containerId: null,
    containerTypeName: null,
    warehouseZonesId: null,
    status: null,
    compartmentCount: null
  },
  rules: {
    batchCount: [
      { required: true, message: '请输入新增数量', trigger: 'blur' },
      { type: 'integer', message: '请输入整数', trigger: 'blur' },
      { 
        validator: (rule, value, callback) => {
          if (value < 1 || value > 1000) {
            callback(new Error('请输入1-1000之间的正整数'))
          } else {
            callback()
          }
        }, 
        trigger: 'blur' 
      }
    ],
    containerTypeId: [
      { required: true, message: '请选择料箱类型', trigger: 'blur' }
    ]
  }
})
const { queryParams, form, rules } = toRefs(data)

// 处理料箱类型选择
const selectType = (e) => {
  // 当选择清空时不处理
  if (!e) return
  
  const index = containerTypeList.value.findIndex(item => item.container_type_id === e)
  if (index !== -1) {
    // 带隔板类型
    if (containerTypeList.value[index].is_divided === true) {
      selectTypeFlag.value = true
      // 设置默认值为20，如果之前没有值的话
      if (form.value.compartmentCount === undefined || form.value.compartmentCount === null) {
        form.value.compartmentCount = 20
      }
    } else {
      // 不带隔板类型
      selectTypeFlag.value = false
      form.value.compartmentCount = null
    }
  }
}

// 重置类型选择（当点击清除按钮时）
const resetTypeSelection = () => {
  selectTypeFlag.value = false
  form.value.compartmentCount = null
}

/** 查询料箱列表 */
function getList() {
  loading.value = true
  listContainer(queryParams.value).then(res => {
    if (res.errCode === '1') {
      containerList.value = res.data.page.records
      total.value = res.data.page.total
      loading.value = false
    }
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    batchCount: null,
    containerId: null,
    containerTypeId: null,
    storageId: null,
    warehouseZonesId: null,
    status: null,
    compartmentCount: null,
    createdBy: null,
    updateBy: null,
    updateTime: null,
    createTime: null,
    aBoxFaceCode: null,
    bBoxFaceCode: null
  }
  proxy.resetForm("containerRef")
  selectTypeFlag.value = false
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.containerId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加料箱"
  currentMode.value = 'add'
  getContainerType()
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _containerId = row.containerId || ids.value
  getContainer(_containerId).then(res => {
    form.value = res.data.container
    open.value = true
    title.value = "修改料箱"
    currentMode.value = 'edit'
    getContainerType().then(() => {
      // 编辑时根据当前类型初始化状态
      if (form.value.containerTypeId) {
        selectType(form.value.containerTypeId)
      }
    })
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["containerRef"].validate(valid => {
    if (valid) {
      if (form.value.containerId != null) {
        updateContainer(form.value).then(res => {
          if (res.errCode === '1') {
            proxy.$modal.msgSuccess("修改成功")
            open.value = false
            getList()
          } else {
            proxy.$modal.msgError(res.msg)
          }
        })
      } else {
        addContainer(form.value).then(res => {
          if (res.errCode === '1') {
            proxy.$modal.msgSuccess("新增成功")
            open.value = false
            getList()
          } else {
            proxy.$modal.msgError(res.msg)
          }
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _containerIds = row.containerId || ids.value
  proxy.$modal.confirm('是否确认删除料箱编号为"' + _containerIds + '"的数据项？').then(function() {
    return delContainer(_containerIds)
  }).then(res => {
    if (res.errCode === '1') {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    } else {
      proxy.$modal.msgError(res.msg)
    }
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('/api/container/export', {
    ...queryParams.value
  }, `料箱数据_${new Date().getTime()}.xlsx`)
}

// 下载模板
const downloadContainer = async() => {
  proxy.download('/api/container/downloadTemplate', {}, `料箱模板_${new Date().getTime()}.xlsx`)
}

// 上传成功后的回调
const handleUploadSuccess = (res) => {
  getList()
}

// 部分成功回调
const handleUploadWarning = (res) => {
  getList()
}

// 获取料箱类型的ID和名称
const getContainerType = async() => {
  const res = await getContainerTypeAPI()
  containerTypeList.value = res.data.list.filter(item => {
    return item.container_category === 1
  })
}

const submitFormBatch = () => {
  proxy.$refs["containerBatchRef"].validate(async(valid) => {
    if (valid) {
      const msgInstance = ElMessage({
        message: '正在为料箱创建对应的储格信息, 请稍等...',
        type: 'warning',
        duration: 0,
        showClose: false
      })
      try {
        btn.batchAdd = true
        const res = await batchAddAPI(form.value)
        if (res.errCode === '1') {
          proxy.$modal.msgSuccess("新增成功")
          openBatch.value = false
          getList()
        } else {
          proxy.$modal.msgError(res.msg)
        }
      } finally {
        btn.batchAdd = false
        msgInstance?.close()
      }
    }
  })
}

const batchAdd = () => {
  reset()
  openBatch.value = true
  getContainerType()
}

const cancelBatch = () => {
  openBatch.value = false
  reset()
}

getContainerType()
getList()
</script>
    